package com.kehutong.material.app;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.kehutong.material.service.impl.MaterialServiceImpl;
import org.coraframework.http.HttpClient;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.connection.ThreadLocalCache;
import org.coraframework.orm.jdbc.execute.entity.FindArray;
import org.coraframework.threadpool.ThreadPool;
import org.coraframework.util.CallBack;
import org.coraframework.util.Objects;
import org.coraframework.util.time.TimeUtil;
import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.ErrorCode;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.urlconfig.WebUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.material.entity.Material;
import com.kehutong.material.enums.MaterialType;
import com.kehutong.material.urlConfig.WorkerUrlConfig;

/**
 * 素材
 *
 * @Author: liuzhen (liuxing521a@163.com)
 * @Date: 20/4/16 上午9:39
 */
@MvcAction
@ReqMapping("/kht-bin/material")
public class MaterialAction {

    private static final Logger logger = LoggerFactory.getLogger(MaterialAction.class);


    @Inject
    private FileUrlConfig fileUrlConfig;
    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DoveClient doveClient;
    @Inject
    private MaterialServiceImpl materialService;


    @ReqMapping("/list")
    public Object list(Token token, JSONObject jsonObject) throws Exception {

        final List<Material> folderList = jdbcSession.findArray(Material.class)
                .eq(jsonObject, "type", "pid")
                .like(jsonObject, "name")
                .eq("isFolder", true)
                .eq("deleted", false)
                .exe();

        final FindArray<Material> find = jdbcSession.findArray(Material.class)
                .eq(jsonObject, "type")
                .like(jsonObject, "name")
                .eq("isFolder", false)
                .eq("deleted", false);
        final String pid = jsonObject.getString("pid");
        if (Objects.nonEmpty(pid))
            find.eq("pid", pid);

        //原来的逻辑Root节点的pid不是1,所有匹配'1-%'的文件
        /*if (Root.isRoot(pid)) {
            find.like("pid", Root.toRoot(Root.ROOT_ID), LikeType.RIGHT);
        } else {
            find.eq("pid", pid);
        }*/

        final List<Material> questionList = find.exe();
        for (Material me : questionList) {
            if (Objects.isEmpty(me.getType().getName())) {
                continue;//非文件，图片，视频类型
            }

            if (Objects.nonNull(me.getExpiredTime()) &&
                    me.getExpiredTime().isAfter(LocalDateTime.now())) {
                continue;//没过期
            }

            materialService.forwordFile(token.getCompanyNo(), me);
        }

        final List<JSONObject> list = new ArrayList<>(questionList.size() + folderList.size());
        folderList.forEach(item -> list.add(toJson(item)));
        questionList.forEach(item -> list.add(toJson(item)));

        return Result.success(list);
    }

    private JSONObject toJson(Material material) {
        final JSONObject jsonObject = new JSONObject();

        jsonObject.put("id", material.getId());
        jsonObject.put("name", material.getName());
        jsonObject.put("fileType", material.getType().getId());
        jsonObject.put("fileId", material.getFileId());
        jsonObject.put("shareUrl", material.getShareUrl());
        jsonObject.put("memory", material.getMemory());
        jsonObject.put("media_id", material.getMedia_id());
        jsonObject.put("desc", material.getDescrition());
        jsonObject.put("type", "4");

        return jsonObject;
    }


    @ReqMapping("/file/list")
    public Object fileList(Token token, JSONObject jsonObject){
        List<Material> folderList = jdbcSession.findArray(Material.class)
                                               .eq(jsonObject, "type", "pid")
                                               .like(jsonObject, "name")
                                               .eq("isFolder", false)
                                               .eq("deleted", false)
                                               .exe();
        for (Material me : folderList) {
            if (Objects.isEmpty(me.getType().getName())) {
                continue;//非文件，图片，视频类型
            }

            if (Objects.nonNull(me.getExpiredTime()) &&
                me.getExpiredTime().isAfter(LocalDateTime.now())) {
                continue;//没过期
            }

            materialService.forwordFile(token.getCompanyNo(), me);
        }
        return Result.success(folderList);
    }

    @ReqMapping("/folder/list")
    public Object folderList(JSONObject jsonObject){
        List<Material> folderList = jdbcSession.findArray(Material.class)
                                               .eq(jsonObject, "type", "pid")
                                               .like(jsonObject, "name")
                                               .eq("isFolder", true)
                                               .eq("deleted", false)
                                               .exe();
        return Result.success(folderList);
    }

    @ReqMapping("/search")
    public Object search(JSONObject jsonObject){
        List<Material> folderList = jdbcSession.findArray(Material.class)
                                               .eq(jsonObject, "type", "pid")
                                               .like(jsonObject, "name")
                                               .eq("isFolder", false)
                                               .eq("deleted", false)
                                               .exe();
        return Result.success(folderList);
    }

    @ReqMapping("/get")
    public Object getMaterial(Token token, String id) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token);
        jsonObject.put("id",id);
        return materialService.getMaterial(jsonObject);
    }


    /**
     * 群发
     */
    @ReqMapping("/send")
    public Object sendMsg(String companyNo, JSONObject req) throws Exception {
//        final String type = req.getString("type");
//        //final String access_token = enterpriseService.getContactAccessToken(companyNo);
//        //todo 设置参数
//        JSONObject dataJsonObject = doveClient.post("/xxx", (httpOne) -> {
//            httpOne.addParam("companyNo", companyNo);
//        });
//        final String access_token = dataJsonObject.getString("data");
//
//        JSONArray externalUserIds = JSONObject.parseArray(req.getString("externalUserIds"));
//        final CallBack<HttpClient> httpCallBack = http -> {
//            http.addParam("access_token", access_token);
//
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("chat_type", "single");
//            // sender 发送企业群发消息的成员userid，当类型为发送给客户群时必填
////            jsonObject.put("sender", "HuangShu");
////            jsonObject.put("external_userid", req.getJSONArray("externalUserIds"));
//            jsonObject.put("external_userid", externalUserIds);
//
//            JSONObject link = new JSONObject();
//            Material material = Pool.get(Material.class, req.getString("materialId"));
//            link.put("title", material.getName());
//            link.put("desc", material.getDescrition());
//            link.put("picurl", fileUrlConfig.getUrl("/file/view", "isBig", "true", "id", material.getFileId()));
//            switch (EnumUtil.getEnum(MaterialType.class, type)) {
//                case FILE:
//                    link.put("url", fileUrlConfig.getFile(material.getFileId(), true));
//                    break;
//                case IMAGE:
//                    link.put("url", fileUrlConfig.getUrl("/file/view", "isBig", "true", "id", material.getFileId()));
//                    break;
//                case VIDEO:
//                    link.put("url", fileUrlConfig.getVideo(material.getFileId()));
//                    break;
//                case SHARE:
//                    link.put("url", material.getShareUrl());
//                    break;
//                case GRAPHIC:
//                    link.put("url", webUrlConfig.getUrl("/graphic/show?id=" + material.getId()));
//                    break;
//                default:
//                    break;
//            }
//            jsonObject.put("link", link);
//
//            logger.trace("accToken:{}, externalUserIds:{}", access_token, externalUserIds);
//            logger.trace("link:{}, jsonObject:{}, http:{}", link, jsonObject.toJSONString(), http);
//
//            http.setBody(jsonObject.toJSONString());
//        };

       /* AtomicReference<JSONObject> jsonObjectAtomic = new AtomicReference<>();
        ErrorCode rs = workConfig.post("/cgi-bin/externalcontact/add_msg_template", httpCallBack, json -> {
            logger.trace("sendMsg {}", json);
            jsonObjectAtomic.set(json);

            return;
        });*/

       /* JSONArray fail_list = new JSONArray();
        JSONObject jsonObject = jsonObjectAtomic.get();
        if (Objects.nonNull(jsonObject)) {
            fail_list = jsonObject.getJSONArray("fail_list");

            if (Objects.isEmpty(fail_list)) {
                return com.kehutong.common.errcode.Result.success(fail_list);
            }
        }

        if (rs.code == 41048) {
            fail_list = externalUserIds;
        }
        return com.kehutong.common.errcode.Result.success(fail_list);*/
        return null;
    }

    @ReqMapping("/get/content")
    public Object getMaterialContent(String companyNo, String id) throws Exception {
        ThreadLocalCache.current().setCorpId(companyNo);
        Material material = Pool.get(Material.class, id);
        return Result.success(material);
    }

   /* private JSONObject toJson(Folder folder) {
        final JSONObject jsonObject = new JSONObject();

        jsonObject.put("id", folder.getId());
        jsonObject.put("name", folder.getName());
        jsonObject.put("type", "1");

        return jsonObject;
    }*/


}
